let timer = null;
let baseUrl = 'https://test.baodanxia.com.cn/api';

import { wxLoginCodeApi, accountLoginApi } from './api';
import $store from '../store/index';

export default {
	// 通知框
	toast(text, duration, success) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success || 'none',
			duration: duration || 2000
		})
	},
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param {*} postData 请求参数
	 * @param string method 请求方式
	 *  GET or POST
	 * @param string contentType 数据格式
	 *  'application/x-www-form-urlencoded'
	 *  'application/json'
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request(url, postData = {}, method = "POST", isDelay, hideLoading) {
		let that = this;
		//接口请求
		let loading = false;
		timer && uni.hideLoading();
		clearTimeout(timer);
		timer = null;
		if (!hideLoading) {
			timer = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loading = true
					}
				})
			}, isDelay ? 1000 : 0)
		}

		return new Promise((resolve, reject) => {
			uni.request({
				url: baseUrl + url,
				data: postData,
				header: {
					'content-type': 'application/json',
					'Authorization': 'Bearer ' + uni.getStorageSync("loginToken")
				},
				method: method, //'GET','POST'
				success: (res) => {
					if (loading && !hideLoading) {
						uni.hideLoading()
					}
					if (res.statusCode === 200) {
						if (res.data.errno === 401) {
							uni.clearStorageSync(); // 清除所有本地存储
							that.toast('请重新登录',null,'error');
							// 回到首页
							uni.redirectTo({
								url:'/pages/index/index'
							});
						} else if (res.data.errno === 500) {
							that.toast(res.data.msg)
						} else if (res.data.errno === 404) {
							that.toast(res.data.msg)
						} else {
							resolve(res.data);
						}
					} else {
						reject(res.data.msg);
					}
				},
				fail: (res) => {
					that.toast("网络不给力，请稍后再试~")
					reject(res)
				},
				complete: function (res) {
					clearTimeout(timer)
					timer = null;
					if (res.statusCode === 200) {
						if (res.data.errno === 0 || res.data.errno === 401) {
							uni.hideLoading()
						} else {
							that.toast(res.data.msg)
						}
					} else {
						that.toast('服务器开小差了~')
					}
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile(url, src) {
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: utils.interfaceUrl() + url,
				filePath: src,
				name: 'file',
				header: {
					'content-type': 'multipart/form-data',
					'token': utils.getToken()
				},
				success(res) {
					uni.hideLoading()
					let data = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					if (data.errno == 0) {
						//返回图片地址
						resolve(data)
					} else {
						that.toast(res.msg);
					}
				},
				fail(res) {
					utils.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	/**
	 * 调用微信登录获取code
	 */
	wxLoginCode() {
		return new Promise(function (resolve, reject) {
			uni.login({
				success(res) {
					if (res.code) {
						resolve(res);
					} else {
						reject(res);
					}
				},
				fail(err) {
					reject(err);
				}
			});
		});
	},
	/**
	 * 微信登录
	 */
	async wxLogin() {
		let that = this;
		// 获取登录的code
		let res = await that.wxLoginCode();
		if (res && res.code) {
			// 获取openId
			let result = await that.request(wxLoginCodeApi(res.code), {}, 'GET');
			if (result && result.data) {
				let openId = result.data;
				// 登录系统
				let result2 = await that.request(accountLoginApi(), { openId });
				if (result2 && result2.data) {
					// token
					uni.setStorageSync('loginToken', result2.data.accessToken);
					// 用户基础信息
					uni.setStorageSync('loginUser', result2.data);
					that.toast('登录成功', null, 'success');
				}
			}
		}
	}
}